import http from '../utils/http';
import { setAuthorizationToken, saveToken,removeToken } from '../utils/jwtToken';
import jwtDecode from 'jwt-decode';
import { SET_CURRENT_USER } from './types';

export function setCurrentUser(user) {
  return {
    type: SET_CURRENT_USER,
    user
  };
}

export function logout() {
  return dispatch => {
    removeToken();
    setAuthorizationToken(false);
    dispatch(setCurrentUser({}));
  }
}

export function login(data) {
  return dispatch => {
    return http.post('/api/auth/login', data).then(res => {
          const token = res.data.token;
          saveToken(token);
          setAuthorizationToken(token);
          dispatch(setCurrentUser(jwtDecode(token)));
        });
  }
}

export function register(data){
  return dispatch => {  
    return http.post('/api/auth/register',data).then(res => {
      if (!res.data.err){
        const token = res.data.token;
        saveToken(token);
        setAuthorizationToken(token);
        dispatch(setCurrentUser(jwtDecode(token)));
      }
    });
  }
}